package com.lindroy.androidplayer.logic.network2

import com.franmontiel.persistentcookiejar.PersistentCookieJar
import com.franmontiel.persistentcookiejar.cache.SetCookieCache
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor
import com.ihsanbal.logging.Level
import com.ihsanbal.logging.LoggingInterceptor
import com.lindroy.androidplayer.base.App
import okhttp3.OkHttpClient
import okhttp3.internal.platform.Platform
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

/**
 * @author Lin
 * @date 2021/4/15
 * @function  网络请求构建器
 */

val apiService: ApiService by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
    NetworkService.instance.create(ApiService::class.java)
}

class NetworkService : BaseNetworkService() {
    companion object {
        val instance: NetworkService by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            NetworkService()
        }
    }

    override fun setHttpClientBuilder(builder: OkHttpClient.Builder): OkHttpClient.Builder =
        builder.run {
            cookieJar(cookieJar)
            addInterceptor(
                LoggingInterceptor.Builder()
                    .setLevel(Level.BASIC)
                    .log(Platform.INFO)
                    .tag("HttpRequest")
//                .addHeader("cityCode", "53")
//                .addQueryParam("moonStatus", "crescent")
                    .build()
            )

        }

    override fun setRetrofitBuilder(builder: Retrofit.Builder): Retrofit.Builder = builder.also {
        it.addConverterFactory(GsonConverterFactory.create())//日志拦截器
    }

    private val cookieJar: PersistentCookieJar by lazy {
        PersistentCookieJar(SetCookieCache(), SharedPrefsCookiePersistor(App.context))
    }

    fun clearCookie() = cookieJar.clear()
}